package cn.tedu.weibo01.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile pic) throws IOException {
//        pic代表客户端上传的文件参数
        System.out.println("pic = " + pic);
        String fileName = pic.getOriginalFilename();
        System.out.println("原始文件名:"+fileName);
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;
        System.out.println("唯一文件名:"+fileName);
//        准备保存图片的路径
        String dirPath = "E:/files";
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+"/"+fileName;
        pic.transferTo(new File(filePath));

//        把图片的url路径响应给客户端
        return "/"+fileName;
    }
    @RequestMapping("/remove")
    public void remove(String url){
        new File("e:/files"+url).delete();
    }
}
